package admin

import (
	"fmt"
	"os"
	"regexp"
	"strconv"
	"strings"
	"tcsc/models"
	"tcsc/sword"
	"time"

	"github.com/360EntSecGroup-Skylar/excelize"
	"github.com/astaxie/beego"
)

type Member struct {
	BaseController
}

func (c *Member) Get() {
	gid := c.Gid
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	vid := c.GetString("vid")
	search := c.GetString("search")
	lt := ` limit ` + page + `,` + num
	ob := ` order by a.addtime desc`
	c.Data["vid"] = vid
	// if gid == "0" {
	// 	var w []string
	// 	w = append(w, `a.status=1`)
	// 	sql := `select a.*,c.pathname from mt_member a left join mt_resources c
	// 			on a.avatar=c.id where `
	// 	sql2 := `select count(a.id) as totals from mt_member a where `
	// 	if search != "" {
	// 		w = append(w, `(a.monicker like '%`+search+`%' or a.name like '%`+search+`%' or a.mobile like '%`+search+`%')`)
	// 	} else {
	// 		if vid != "" {
	// 			sql = `select a.*,c.pathname from mt_member a left join mt_resources c
	// 			on a.avatar=c.id join (select * from mt_member_vip_order where vid=` + vid + `) b on a.id=b.uid where `
	// 			sql2 = `select count(a.id) as totals from mt_member a join (select * from mt_member_vip_order where vid=` + vid + `) b on a.id=b.uid where `
	// 		}
	// 	}
	// 	ws := strings.Join(w, ` and `)
	// 	sql = sql + ws + ob + lt
	// 	sql2 = sql2 + ws
	// 	info := models.Query(sql)
	// 	for i, v := range info {
	// 		vip := models.Query(`
	// 			select b.name
	// 			from mt_member_vip_order a
	// 			join (select * from mt_member_vip where gid=? and status=1) b on a.vid=b.id
	// 			where a.uid=?`, c.Gid, v["id"])
	// 		if person := models.Query(`select b.gid from mt_member_vip_order a left join mt_member_vip b on a.vid=b.id where a.uid=?`, v["id"]); person != nil {
	// 			if person[0]["gid"].(string) != c.Gid {
	// 				info[i] = nil
	// 			}
	// 		}
	// 		if person := models.Query(`select * from mt_member_vip_order where uid=?`, v["id"]); person == nil {
	// 			if search == "" && c.Gid != "0" {
	// 				info[i] = nil
	// 			}
	// 		}
	// 		if vip != nil {
	// 			v["vname"] = vip[0]["name"]
	// 		}
	// 	}
	// 	c.Data["info"] = info
	// 	c.Data["paginator"] = models.Page(sql2, page2, num)
	// } else {
	w := ` a.status = 1`
	if search != "" {
		w += ` and (a.monicker like '%` + search + `%' or a.name like '%` + search + `%' or a.mobile like '%` + search + `%')`
	}
	memberVipSql := `select id from mt_member_vip where status = 1 and gid = ` + gid
	if search != "" && vid == "" || gid == "0" {
		memberVipSql = `select id from mt_member_vip where status = 1 and gid <> ` + gid
	}
	memberVip := models.Query(memberVipSql)
	var vidArr []string
	for _, vid := range memberVip {
		vidArr = append(vidArr, vid["id"].(string))
	}
	vidStr := strings.Join(vidArr, ",")
	vipUidSql := `select uid from mt_member_vip_order where vid in(` + vidStr + `)`
	if vid != "" {
		vipUidSql = `select uid from mt_member_vip_order where vid = ` + vid
	}
	vipUid := models.Query(vipUidSql)
	var uidArr []string
	for _, uid := range vipUid {
		uidArr = append(uidArr, uid["uid"].(string))
	}
	uidStr := strings.Join(uidArr, ",")
	if vid == "" {
		if search != "" || gid == "0" {
			w += ` and a.id not in(` + uidStr + `)`
		} else {
			w += ` and a.id in (` + uidStr + `)`
		}
	} else {
		w += ` and a.id in (` + uidStr + `)`
	}
	if uidStr != "" {
		member := models.Query(`select a.*,b.pathname from mt_member a 
				left join mt_resources b on a.avatar=b.id 
				where` + w + ob + lt)
		pageSql := `select count(a.id) as totals from mt_member a where` + w
		for _, people := range member {
			id := people["id"].(string)
			vip := models.Query(`select a.name from mt_member_vip a 
					left join mt_member_vip_order b on a.id = b.vid 
					where a.status = 1 and b.uid = ? and a.gid = ?`, id, gid)
			if vip != nil {
				people["vipName"] = fmt.Sprint(vip[0]["name"])
			}
		}
		c.Data["info"] = member
		c.Data["paginator"] = models.Page(pageSql, page2, num)
	}

	c.Data["url"] = `/admin/member/index?search=` + search + `&vid=` + vid + `&`
	c.Data["vip"] = models.Query(`select * from mt_member_vip where status=1 and gid=?`, c.Gid)
	if c.Gid == "0" {
		c.TplName = "admin/member/index.html"
	} else {
		c.TplName = "admin/member/index_g.html"
	}
}

type MemberVipExport struct {
	beego.Controller
}

func (c *MemberVipExport) Get() {
	return
	// sql := `select c.name,b.monicker,b.mobile from mt_member_vip_order a
	// 		left join mt_member b on a.uid=b.id
	// 		left join mt_member_vip c on a.vid=c.id
	// 		where a.vid in (select id from mt_member_vip where status=1 and gid=0) and b.status=1 and b.censoring=1`

	sql := `select monicker, mobile from mt_member 
			where id not in (select a.uid from mt_member_vip_order a left join mt_member_vip b on a.vid=b.id where b.status=1) and status=1 and censoring=1`
	res := models.Query(sql)
	xlsx := excelize.NewFile()

	xlsx.SetCellValue("Sheet1", "A1", "会员")
	xlsx.SetCellValue("Sheet1", "B1", "名字")
	xlsx.SetCellValue("Sheet1", "C1", "电话")

	k := 1
	for _, v := range res {
		k += 1
		kStr := strconv.Itoa(k)
		xlsx.SetCellValue("Sheet1", "A"+kStr, "普通会员")
		xlsx.SetCellValue("Sheet1", "B"+kStr, v["monicker"])
		xlsx.SetCellValue("Sheet1", "C"+kStr, v["mobile"])
	}
	err := os.MkdirAll("static/xlsx", 0777)
	if err != nil {
		beego.Debug(err)
		return
	}
	fileName := "会员"
	pathname := "static/xlsx/" + fileName + ".xlsx"
	err = xlsx.SaveAs(pathname)
	if err != nil {
		beego.Debug(err)
		return
	}
	js := make(map[string]interface{})
	js["status"] = 1
	js["pathname"] = pathname
	c.Data["json"] = js
	c.ServeJSON()
}

type MemberOrder struct {
	BaseController
}

func (c *MemberOrder) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	status := c.GetString("status")
	if status != "" {
		w = append(w, `a.status=`+status)
	} else {
		w = append(w, `a.status>0 and a.status<6`)
	}
	c.Data["status"] = status
	id := c.GetString("id")
	if id == "" {
		return
	} else {
		w = append(w, `a.uid=`+id)
	}
	search := c.GetString("search")
	if search != "" {
		w = append(w, `a.ordernum like '%`+search+`%'`)
	}
	stime := c.GetString("stime")
	c.Data["stime"] = stime
	if stime != "" {
		w = append(w, `a.addtime>'`+stime+`'`)
	}
	etime := c.GetString("etime")
	c.Data["etime"] = etime
	if etime != "" {
		w = append(w, `a.addtime<='`+etime+`'`)
	}
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num
	ob := ` order by a.addtime desc`
	sql := `select a.*,c.pathname,b.monicker,d.name as shen,e.name as shi,f.name as qu from mt_order a left join mt_member b on a.uid=b.id 
	left join mt_resources c on b.avatar=c.id left join mt_area d on a.province=d.code left join mt_area e on a.city=e.code left join mt_area 
	f on a.area=f.code where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_order a where ` + ws
	info := models.Query(sql)
	for _, i := range info {
		carid := fmt.Sprint(i["carid"])
		product := models.Query(`select a.*,b.title,b.model,b.isw,b.length,b.height,b.width,b.weight,b.number,a.price as price,c.pathname,d.monicker
		 from mt_order_car a left join mt_product b on a.pid=b.id left join mt_resources c on b.img=c.id left join mt_member d
		  on a.did=d.id where a.id in(` + carid + `)`)
		var tj = "0.00"
		var zl = "0.00"
		for _, v := range product {
			isw := fmt.Sprint(v["isw"])
			width := fmt.Sprint(v["width"])
			height := fmt.Sprint(v["height"])
			length := fmt.Sprint(v["length"])
			weight := fmt.Sprint(v["weight"])
			number := fmt.Sprint(v["number"])
			num := fmt.Sprint(v["num"])
			weight = sword.Divi(sword.Mult(sword.Mult(weight, number), num), "1000")
			v["weight"] = weight
			vtj := sword.Mult(length, sword.Mult(height, width))
			vtj = sword.Mult(vtj, num)
			v["tj"] = sword.Divi(vtj, "1000000")
			if isw == "0" {
				tj = sword.Sum(tj, vtj)
			} else {
				zl = sword.Sum(zl, weight)
			}
			price := fmt.Sprint(v["price"])
			pprice := sword.Mult(number, price)
			v["pprice"] = pprice
			if status := fmt.Sprint(v["status"]); status == "3" || status == "4" {
				lostnum := sword.Cut(fmt.Sprint(v["num"]), fmt.Sprint(v["sendnum"]))
				if lostnum != "0.00" {
					pprice = sword.Mult(pprice, lostnum)
					v["rprice"] = pprice
				}
			}
		}
		i["tj"] = sword.Divi(tj, "1000000")
		i["zl"] = zl
		i["product"] = product

		rmoney := models.Query(`select sum(money) as money from mt_member_money_detail where type=7 and oid=?`, i["id"])[0]["money"]
		if rmoneys := fmt.Sprint(rmoney); rmoneys != "<nil>" {
			i["rmoney"] = rmoneys
			i["smoney"] = sword.Divi(fmt.Sprint(i["money"]), rmoneys)
		}

	}
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/member/order?id=` + id + `+&status=` + status + `&search=` + search + `&`
	c.Data["urlc"] = `/admin/member/order?id=` + id

	c.TplName = "admin/member/order.html"
}

type MemberPromote struct {
	BaseController
}

func (c *MemberPromote) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	t := c.GetString("t")
	c.Data["t"] = t
	if t != "" {
		w = append(w, `a.type=`+t)
	} else {
		w = append(w, `a.type>0`)
	}
	w = append(w, `a.status=1`)
	search := c.GetString("search")
	if search != "" {
		w = append(w, `(a.monicker like '%`+search+`%' or a.name like '%`+search+`%')`)
	}
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num
	ob := ` order by a.addtime desc`
	sql := `select a.*,c.pathname from mt_member a left join mt_resources c 
	on a.avatar=c.id where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_member a where ` + ws
	info := models.Query(sql)
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/member/promote?search=` + search + `&t=` + t + `&`
	c.TplName = "admin/member/promote.html"
}

type MemberAE struct {
	BaseController
}

func (c *MemberAE) Get() {
	c.Data["vip"] = models.Query(`select id,name from mt_member_vip where status=1 and gid=?`, c.Gid)
	id := c.GetString("id")
	if id != "" {
		if info := models.Query(`select a.*,b.pathname from mt_member a left join mt_resources b on a.avatar=b.id where a.id=` + id); info != nil {
			c.Data["info"] = info[0]
			vip := models.Query(`select a.vid from mt_member_vip_order a left join mt_member_vip b on a.vid=b.id where b.gid=? and a.uid=?`, c.Gid, id)
			if vip != nil {
				c.Data["vid"] = vip[0]["vid"]
			}
		} else {
			c.Ctx.Redirect(302, "/admin/member/index")
		}
	}
	if c.Gid == "0" {
		c.TplName = "admin/member/ae.html"
	} else {
		c.TplName = "admin/member/ae_g.html"
	}

}
func (c *MemberAE) Post() {
	defer c.ServeJSON()
	input := c.Input()
	vip := c.GetString("vip")
	uid := c.GetString("id")
	nowtimes := sword.Gettimes("")
	if vip != "0" {
		vips := models.Query(`
			select b.name 
			from mt_member_vip_order a 
			join (select * from mt_member_vip where gid=? and status=1) b on a.vid=b.id 
			where a.uid=?`, c.Gid, uid)
		if vips != nil {
			if err := models.Exec(`update mt_member_vip_order set vid=?,addtime=? where uid=?`, vip, nowtimes, uid); err != nil {
				beego.Debug(err)
			}
		} else {
			if err := models.Exec(`insert into mt_member_vip_order (vid,uid,addtime) values (?,?,?)`, vip, uid, nowtimes); err != nil {
				beego.Debug(err)
			}
		}
	} else {
		var vid []string
		vips := models.Query(`select id from mt_member_vip where status=1 and gid=?`, c.Gid)
		for _, v := range vips {
			vid = append(vid, fmt.Sprint(v["id"]))
		}
		vids := strings.Join(vid, ",")
		if vids != "" {
			if err := models.Exec(`delete from mt_member_vip_order where uid=? and vid in(`+vids+`)`, uid); err != nil {
				beego.Debug(err)
			}
		}
	}
	// old := models.Query(`select money from mt_member where id=?`, uid)[0]["money"]
	if res, err := models.Save("mt_member", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		var r models.Mt_systems_record
		r.Tid = int(res)
		if input.Get("id") == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 9
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
		// money := c.GetString("money")
		// if money != "" {
		// 	if err := models.Exec(`insert into mt_systems_record (uid,table,addtime,way,tid,content) values (?,9,?,77,?,?)
		// 		`, c.Qid, sword.Gettimes(""), uid, fmt.Sprintf(`将余额从%v 设置成 %v`, old, money)); err != nil {
		// 		beego.Debug(err)
		// 	}
		// }
	}
}

type MemberContent struct {
	BaseController
}

func (c *MemberContent) Get() {
	id := c.GetString("id")
	if info := models.Query(`select a.*,b.pathname,c.name as shen,d.name as shi,e.name as qu from mt_member a left join 
		mt_resources b on a.avatar=b.id left join mt_area c on a.province=c.id left join mt_area d on a.city=d.id left join 
		mt_area e on a.area=e.id where a.id=` + id); info != nil {
		c.Data["info"] = info[0]
	} else {
		c.Ctx.Redirect(302, "/admin/member/index")
	}
	c.TplName = "admin/member/content.html"
}

type MemberVip struct {
	BaseController
}

func (c *MemberVip) Get() {
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	var w []string
	w = append(w, `a.status=1`)
	w = append(w, `a.gid=`+c.Gid)
	ws := strings.Join(w, ` and `)
	lt := ` limit ` + page + `,` + num
	sql := `select a.*,c.pathname from mt_member_vip a left join mt_resources c 
	on a.img=c.id where ` + ws + lt
	sql2 := `select count(a.id) as totals from mt_member_vip a where ` + ws
	info := models.Query(sql)
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/member/vip?`
	c.TplName = "admin/member/vip.html"
}

type MemberVipAE struct {
	BaseController
}

func (c *MemberVipAE) Get() {
	id := c.GetString("id")
	if id != "" {
		if info := models.Query(`select a.*,b.pathname from mt_member_vip a left join 
		mt_resources b on a.img=b.id where a.gid=? and a.id=?`, c.Gid, id); info != nil {
			c.Data["info"] = info[0]
		} else {
			c.Ctx.Redirect(302, "/admin/member/vip")
		}
	}
	c.TplName = "admin/member/vip_ae.html"
}
func (c *MemberVipAE) Post() {
	defer c.ServeJSON()
	input := c.Input()
	if input.Get("id") == "" {
		input.Set("addtime", sword.Gettimes("2006-01-02 15:04:05"))
	}
	input.Set("gid", c.Gid)
	if res, err := models.Save("mt_member_vip", input); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		var r models.Mt_systems_record
		r.Tid = int(res)
		if input.Get("id") == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 10
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
}

type MemberVipOrder struct {
	BaseController
}

func (c *MemberVipOrder) Get() {
	id := c.GetString("id")
	if vip := models.Query(`select name from mt_member_vip where id=` + id); vip != nil {
		c.Data["v"] = vip[0]["name"]
		page, page2, num := models.Pagechange(c.GetString("page"), "")
		var w []string
		w = append(w, `a.vid=id`)
		ws := strings.Join(w, ` and `)
		lt := ` limit ` + page + `,` + num
		ob := ` order by a.addtime desc`
		sql := `select a.*,b.monicker,c.pathname from mt_member_vip_order a left join mt_member b on a.uid=b.id left join mt_resources c 
	on b.avatar=c.id where ` + ws + ob + lt
		sql2 := `select count(a.id) as totals from mt_member_vip_order a where ` + ws
		info := models.Query(sql)
		c.Data["info"] = info
		c.Data["paginator"] = models.Page(sql2, page2, num)
		c.Data["url"] = `/admin/member/vip_order?id=` + id + `&`
		c.TplName = "admin/member/vip_order.html"
	} else {
		c.Ctx.Redirect(302, "/admin/member/vip")
	}
}

type MemberMoney struct {
	BaseController
}

func (c *MemberMoney) Get() {
	id := c.GetString("id")
	t := c.GetString("t")
	var w []string
	w = append(w, `a.uid=`+id)
	if t != "" {
		w = append(w, `a.type=`+t)
	}
	c.Data["t"] = t
	c.Data["uid"] = id
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	lt := ` limit ` + page + `,` + num
	ws := strings.Join(w, ` and `)
	ob := ` order by a.addtime desc`
	sql := `select a.*,b.monicker,c.pathname,d.ordernum from mt_member_money_detail a left join mt_member b on a.uid=b.id left join 
		mt_resources c on b.avatar=c.id left join mt_order d on a.oid=d.id where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_member_money_detail a where ` + ws
	info := models.Query(sql)
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/member/money?id=` + id + `&t=` + t + `&`
	c.Data["urls"] = `/admin/member/money?id=` + id
	c.TplName = "admin/member/money.html"
}

type MemberMoneyExport struct {
	BaseController
}

func (c *MemberMoneyExport) Get() {
	id := c.GetString("id")
	t := c.GetString("t")
	var w []string
	w = append(w, `a.uid=`+id)
	if t != "" {
		w = append(w, `a.type=`+t)
	}
	ws := strings.Join(w, ` and `)
	ob := ` order by a.type, a.addtime desc`
	sql := models.Query(`select a.*,b.ordernum from mt_member_money_detail a 
		left join mt_order b on b.id=a.oid 
		where ` + ws + ob)
	name := models.Query(`select monicker from mt_member where id=?`, id)[0]["monicker"]
	xlsx := excelize.NewFile()
	xlsx.SetCellValue("Sheet1", "A1", "顾客")
	xlsx.SetCellValue("Sheet1", "B1", "操作")
	xlsx.SetCellValue("Sheet1", "C1", "金额")
	xlsx.SetCellValue("Sheet1", "D1", "支付方式")
	xlsx.SetCellValue("Sheet1", "E1", "订单号")
	xlsx.SetCellValue("Sheet1", "F1", "时间")
	k := 1
	for _, v := range sql {
		k += 1
		key := strconv.Itoa(k)
		handle := ""
		paytype := ""
		switch v["type"].(string) {
		case "0":
			handle = "充值"
		case "1":
			handle = "提现"
		case "2":
			handle = "分销提成"
		case "3":
			handle = "购买商品"
		case "4":
			handle = "推广佣金"
		case "5":
			handle = "店铺收入"
		case "6":
			handle = "退款"
		case "7":
			handle = "店铺退款支出"
		case "8":
			handle = "红包"
		}
		switch fmt.Sprint(v["paytype"]) {
		case "1":
			paytype = "余额"
		case "2":
			paytype = "微信"
		case "3":
			paytype = "支付宝"
		}
		xlsx.SetCellValue("Sheet1", "A"+key, name)
		xlsx.SetCellValue("Sheet1", "B"+key, handle)
		xlsx.SetCellValue("Sheet1", "C"+key, v["money"])
		xlsx.SetCellValue("Sheet1", "D"+key, paytype)
		xlsx.SetCellValue("Sheet1", "E"+key, v["ordernum"])
		xlsx.SetCellValue("Sheet1", "F"+key, v["addtime"])
	}
	err := os.MkdirAll("static/xlsx", 0777)
	if err != nil {
		beego.Debug(err)
		return
	}
	fileName := "充值消费记录表"
	pathname := "static/xlsx/" + fileName + ".xlsx"
	err = xlsx.SaveAs(pathname)
	if err != nil {
		beego.Debug(err)
		return
	}
	c.Ctx.Redirect(302, "/"+pathname)
}

type MemberIntegral struct {
	BaseController
}

func (c *MemberIntegral) Get() {
	id := c.GetString("id")
	t := c.GetString("t")
	var w []string
	w = append(w, `a.uid=`+id)
	if t != "" {
		w = append(w, `a.type=`+t)
	}
	c.Data["t"] = t
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	lt := ` limit ` + page + `,` + num
	ws := strings.Join(w, ` and `)
	ob := ` order by a.addtime desc`
	sql := `select a.*,b.monicker,c.pathname,d.ordernum,e.title as pname from mt_member_integral a left join mt_member b on a.uid=b.id left join 
		mt_resources c on b.avatar=c.id left join mt_order d on a.oid=d.id left join mt_product_integral e on a.pid=e.id where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_member_integral a where ` + ws
	info := models.Query(sql)
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/member/integral?id=` + id + `&t=` + t + `&`
	c.Data["urls"] = `/admin/member/integral?id=` + id
	c.TplName = "admin/member/integral.html"
}

type MemberPromoteList struct {
	BaseController
}

func (c *MemberPromoteList) Get() {
	id := c.GetString("id")
	var w []string
	w = append(w, `a.uid=`+id)
	w = append(w, `a.status=1`)
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	lt := ` limit ` + page + `,` + num
	ws := strings.Join(w, ` and `)
	ob := ` order by a.addtime desc`
	sql := `select a.*,c.pathname from mt_member a left join mt_resources c on a.avatar=c.id where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_member a where ` + ws
	info := models.Query(sql)
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/member/promote_list?id=` + id + `&`
	c.TplName = "admin/member/promote_list.html"
}

type MemberPromoteDel struct {
	BaseController
}

func (c *MemberPromoteDel) Get() {
	id := c.GetString("id")
	if ress, err := models.Orm().Raw(`update mt_member set type=0 where id=` + id).Exec(); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		var r models.Mt_systems_record
		res, _ := ress.RowsAffected()
		r.Tid = int(res)
		r.Way = 4
		r.Addtime = sword.Timeget()
		r.Table = 58
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
	c.ServeJSON()
}

type MemberPromoteApply struct {
	BaseController
}

func (c *MemberPromoteApply) Get() {
	id := c.GetString("id")
	var w []string
	w = append(w, `a.status=1`)
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	lt := ` limit ` + page + `,` + num
	ws := strings.Join(w, ` and `)
	ob := ` order by a.addtime desc`
	sql := `select a.*,b.monicker,c.pathname,d.pathname as cpath,e.pathname as ipath from mt_promote_add a left join mt_member b on a.uid=b.id 
	left join mt_resources c on b.avatar=c.id left join mt_resources d on a.cardimg=d.id left join mt_resources e on a.imgcard=e.id where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_promote_add a where ` + ws
	info := models.Query(sql)
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/member/promote_apply?id=` + id + `&`
	c.TplName = "admin/member/promote_apply.html"
}

type MemberPromotePush struct {
	BaseController
}

func (c *MemberPromotePush) Get() {
	id := c.GetString("id")
	content := c.GetString("content")
	mem := models.Query(`select b.wx_openid_gzh from mt_promote_add a left join mt_member b on a.uid=b.id where a.id=` + id)[0]
	if err := models.Exec(`update mt_promote_add set censoring=2 where id=` + id); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		data := map[string]map[string]interface{}{
			"first":    {"value": `您申请的推广员未通过`},
			"keyword1": {"value": `推广员`, "color": "#e4393c"},
			"keyword2": {"value": `原因:` + content, "color": "#9c9c9c"},
			"remark":   {"value": `您可以调整后再次审核`},
		}
		models.Push(fmt.Sprint(mem["wx_openid_gzh"]), `o1pZ3qYLVc4jWU51MO5kio9gKOL1aV2hkrEHoVMU6Vc`, data, models.Urlc+"/mobile/my", "")
	}
	if fmt.Sprint(c.Data["json"]) == "1" {
		var r models.Mt_systems_record
		r.Tid, _ = strconv.Atoi(id)
		r.Way = 69
		r.Addtime = sword.Timeget()
		r.Table = 58
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
	c.ServeJSON()
}

type MemberPromoteCensoring struct {
	BaseController
}

func (c *MemberPromoteCensoring) Get() {
	id := c.GetString("id")
	pro := models.Query(`select * from mt_promote_add where id=` + id)[0]
	mem := models.Query(`select b.wx_openid_gzh from mt_promote_add a left join mt_member b on a.uid=b.id where a.id=` + id)[0]
	if err := models.Exec(`update mt_promote_add set censoring=1 where id=` + id); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		if err := models.Exec(fmt.Sprintf(`update mt_member set type=%v where id=%v`, pro["style"], pro["uid"])); err != nil {
			beego.Debug(err)
			c.Data["json"] = 0
		} else {
			c.Data["json"] = 1
			data := map[string]map[string]interface{}{
				"first":    {"value": `您申请的推广员已通过`},
				"keyword1": {"value": `推广员`, "color": "#9c9c9c"},
				"keyword2": {"value": `通过`, "color": "#e4393c"},
				"remark":   {"value": `您可以开始进行推广`},
			}
			models.Push(fmt.Sprint(mem["wx_openid_gzh"]), `o1pZ3qYLVc4jWU51MO5kio9gKOL1aV2hkrEHoVMU6Vc`, data, models.Urlc+"/mobile/my", "")
		}
	}
	if fmt.Sprint(c.Data["json"]) == "1" {
		var r models.Mt_systems_record
		r.Tid, _ = strconv.Atoi(id)
		r.Way = 70
		r.Addtime = sword.Timeget()
		r.Table = 58
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
	c.ServeJSON()
}

type MemberGetCash struct {
	BaseController
}

func (c *MemberGetCash) Get() {
	var w []string
	status := c.GetString("status")
	c.Data["status"] = status
	if status != "" {
		w = append(w, `a.status=`+status)
	}
	w = append(w, `a.uid>0`)
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	lt := ` limit ` + page + `,` + num
	ws := strings.Join(w, ` and `)
	ob := ` order by a.addtime desc`
	sql := `select a.*,b.monicker,c.pathname,d.name as bname,b.mobile,b.country,b.city,b.province,b.money as mmoney from mt_member_getcash a left join mt_member b on a.uid=b.id 
	left join mt_resources c on b.avatar=c.id left join mt_systems_configuration d on a.bank=d.id where ` + ws + ob + lt
	sql2 := `select count(a.id) as totals from mt_member_getcash a where ` + ws
	info := models.Query(sql)
	c.Data["info"] = info
	c.Data["paginator"] = models.Page(sql2, page2, num)
	c.Data["url"] = `/admin/member/getcash?status=` + status + `&`
	c.TplName = "admin/member/getcash.html"
}

type MemberGetCashOk struct {
	BaseController
}

func (c *MemberGetCashOk) Get() {
	id := c.GetString("id")
	mem := models.Query(`select b.wx_openid_gzh from mt_member_getcash a left join mt_member b on a.uid=b.id where a.id=` + id)[0]
	if err := models.Exec(`update mt_member_getcash set status=1 where id=` + id); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		data := map[string]map[string]interface{}{
			"first":    {"value": `您申请的提现通过`},
			"keyword1": {"value": `提现`, "color": "#9c9c9c"},
			"keyword2": {"value": `通过`, "color": "#e4393c"},
			"remark":   {"value": `您可以查看银行信息,如有问题请致电客服`},
		}
		models.Push(fmt.Sprint(mem["wx_openid_gzh"]), `o1pZ3qYLVc4jWU51MO5kio9gKOL1aV2hkrEHoVMU6Vc`, data, models.Urlc+"/mobile/my", "")
	}
	if fmt.Sprint(c.Data["json"]) == "1" {
		var r models.Mt_systems_record
		r.Tid, _ = strconv.Atoi(id)
		r.Way = 70
		r.Addtime = sword.Timeget()
		r.Table = 71
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
	c.ServeJSON()
}

type MemberGetCashPush struct {
	BaseController
}

func (c *MemberGetCashPush) Get() {
	id := c.GetString("id")
	content := c.GetString("content")
	mem := models.Query(`select b.wx_openid_gzh from mt_member_getcash a left join mt_member b on a.uid=b.id where a.id=` + id)[0]
	if err := models.Exec(`update mt_member_getcash set status=2 where id=` + id); err != nil {
		beego.Debug(err)
		c.Data["json"] = 0
	} else {
		c.Data["json"] = 1
		data := map[string]map[string]interface{}{
			"first":    {"value": `您申请的提现未通过`},
			"keyword1": {"value": `提现`, "color": "#e4393c"},
			"keyword2": {"value": `原因:` + content, "color": "#9c9c9c"},
			"remark":   {"value": `如有问题,可以致电客服`},
		}
		models.Push(fmt.Sprint(mem["wx_openid_gzh"]), `o1pZ3qYLVc4jWU51MO5kio9gKOL1aV2hkrEHoVMU6Vc`, data, models.Urlc+"/mobile/my", "")
	}
	if fmt.Sprint(c.Data["json"]) == "1" {
		var r models.Mt_systems_record
		r.Tid, _ = strconv.Atoi(id)
		r.Way = 69
		r.Addtime = sword.Timeget()
		r.Table = 71
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
	c.ServeJSON()
}

type MemberExcel struct {
	BaseController
}

func (c *MemberExcel) Get() {
	c.EnableRender = false

	info := models.Query(`
		select a.monicker,a.id,a.mobile,a.country,a.province,a.city,a.latitude,a.longitude,sum(b.money) as moneys 
		from mt_member a 
		left join (select * from mt_member_money_detail where type=3) b on a.id=b.uid 
		where a.status=1 
		group by a.id 
		order by moneys desc`)
	// utils.Display("info", info)

	xlsx := excelize.NewFile()
	// index := xlsx.NewSheet("Sheet1")

	xlsx.SetCellValue("Sheet1", "A1", "ID")
	xlsx.SetCellValue("Sheet1", "B1", "昵称")
	xlsx.SetCellValue("Sheet1", "C1", "会员等级")
	xlsx.SetCellValue("Sheet1", "D1", "手机号码")
	xlsx.SetCellValue("Sheet1", "E1", "地址")
	xlsx.SetCellValue("Sheet1", "F1", "坐标")
	xlsx.SetCellValue("Sheet1", "G1", "消费额")

	for k, v := range info {
		xlsx.SetCellValue("Sheet1", fmt.Sprintf("A%v", k+2), fmt.Sprint(v["id"]))

		xlsx.SetCellValue("Sheet1", fmt.Sprintf("B%v", k+2), fmt.Sprint(v["monicker"]))

		vname := models.Query(`
			select b.name 
			from mt_member_vip_order a 
			join (select * from mt_member_vip where gid=0) b on a.vid=b.id 
			where a.uid=?`, v["id"])
		if vname != nil {
			xlsx.SetCellValue("Sheet1", fmt.Sprintf("C%v", k+2), vname[0]["name"])
		} else {
			xlsx.SetCellValue("Sheet1", fmt.Sprintf("C%v", k+2), "普通会员")
		}

		xlsx.SetCellValue("Sheet1", fmt.Sprintf("D%v", k+2), fmt.Sprint(v["mobile"]))

		xlsx.SetCellValue("Sheet1", fmt.Sprintf("E%v", k+2), fmt.Sprintf(`%v %v %v`, v["country"], v["province"], v["city"]))

		if v["latitude"] != nil {
			xlsx.SetCellValue("Sheet1", fmt.Sprintf("F%v", k+2), fmt.Sprintf(`%v,%v`, v["latitude"], v["longitude"]))
		} else {
			xlsx.SetCellValue("Sheet1", fmt.Sprintf("F%v", k+2), "")
		}

		if v["moneys"] == nil {
			xlsx.SetCellValue("Sheet1", fmt.Sprintf("G%v", k+2), "0.00")
		} else {
			xlsx.SetCellValue("Sheet1", fmt.Sprintf("G%v", k+2), fmt.Sprint(v["moneys"]))
		}
	}
	nowtimes := fmt.Sprint(time.Now().Unix())
	err := os.MkdirAll("static/xlsx", 0777)
	if err != nil {
		beego.Debug(err)
		return
	}
	err = xlsx.SaveAs("static/xlsx/" + nowtimes + ".xlsx")
	if err != nil {
		beego.Debug(err)
		return
	}

	c.Ctx.Redirect(302, "/static/xlsx/"+nowtimes+".xlsx")
}

type MemberBusiness struct {
	BaseController
}

func (c *MemberBusiness) Get() {
	gid := c.Gid
	page, page2, num := models.Pagechange(c.GetString("page"), "")
	vid := c.GetString("vid")
	search := c.GetString("search")
	lt := ` limit ` + page + `,` + num
	ob := ` order by a.addtime desc`
	c.Data["vid"] = vid
	w := ` a.status = 1 and a.business=1`
	if search != "" {
		w += ` and (a.monicker like '%` + search + `%' or a.name like '%` + search + `%' or a.mobile like '%` + search + `%')`
	}
	memberVipSql := `select id from mt_member_vip where status = 1 and gid = ` + gid
	if search != "" && vid == "" || gid == "0" {
		memberVipSql = `select id from mt_member_vip where status = 1 and gid <> ` + gid
	}
	memberVip := models.Query(memberVipSql)
	var vidArr []string
	for _, vid := range memberVip {
		vidArr = append(vidArr, vid["id"].(string))
	}
	vidStr := strings.Join(vidArr, ",")
	vipUidSql := `select uid from mt_member_vip_order where vid in(` + vidStr + `)`
	if vid != "" {
		vipUidSql = `select uid from mt_member_vip_order where vid = ` + vid
	}
	vipUid := models.Query(vipUidSql)
	var uidArr []string
	for _, uid := range vipUid {
		uidArr = append(uidArr, uid["uid"].(string))
	}
	uidStr := strings.Join(uidArr, ",")
	if vid == "" {
		if search != "" || gid == "0" {
			w += ` and a.id not in(` + uidStr + `)`
		} else {
			w += ` and a.id in (` + uidStr + `)`
		}
	} else {
		w += ` and a.id in (` + uidStr + `)`
	}
	if uidStr != "" {
		member := models.Query(`select a.*,b.pathname,c.id as businessId from mt_member a 
				left join mt_resources b on a.avatar=b.id 
				left join mt_business c on a.id=c.uid 
				where c.status=1 and c.gid=` + c.Gid + ` and` + w + ob + lt)
		pageSql := `select count(a.id) as totals from mt_member a where` + w
		for _, people := range member {
			id := people["id"].(string)
			vip := models.Query(`select a.name from mt_member_vip a 
					left join mt_member_vip_order b on a.id = b.vid 
					where a.status = 1 and b.uid = ? and a.gid = ?`, id, gid)
			if vip != nil {
				people["vipName"] = fmt.Sprint(vip[0]["name"])
			}
		}
		c.Data["info"] = member
		c.Data["paginator"] = models.Page(pageSql, page2, num)
	}

	c.Data["url"] = `/admin/member/index?search=` + search + `&vid=` + vid + `&`
	c.Data["vip"] = models.Query(`select * from mt_member_vip where status=1 and gid=?`, c.Gid)
	c.TplName = "admin/member/business.html"
}

type MemberBusinessDel struct {
	BaseController
}

func (c *MemberBusinessDel) Get() {
	defer c.ServeJSON()
	js := make(map[string]interface{})
	c.Data["json"] = &js
	js["status"] = 0
	uid := c.GetString("id")
	business := models.Query(`select id from mt_business where uid=? and gid=?`, uid, c.Gid)
	err := models.Exec(`update mt_member a, mt_business b set a.business=0, b.status=0 
		where a.id=? and b.uid=? and b.gid=?`, uid, uid, c.Gid)
	if err != nil {
		beego.Debug(err)
		return
	}
	js["status"] = 1
	var r models.Mt_systems_record
	r.Tid, _ = strconv.Atoi(fmt.Sprint(business[0]["id"]))
	r.Way = 4
	r.Addtime = sword.Timeget()
	r.Table = 80
	r.Uid, _ = strconv.Atoi(c.Qid)
	if _, err := models.Orm().Insert(&r); err != nil {
		beego.Debug(err)
	}
}

type MemberBusinessAE struct {
	BaseController
}

func (c *MemberBusinessAE) Get() {
	id := c.GetString("id")
	member := models.Query(`select id,monicker,mobile from mt_member where status=1 and business=0 and censoring=1`)
	for _, v := range member {
		id := v["id"].(string)
		vip := models.Query(`select b.name from mt_member_vip_order a 
			left join mt_member_vip b on a.vid=b.id 
			where b.status=1 and b.gid=0 and a.uid=?`, id)
		if vip != nil {
			v["vipName"] = fmt.Sprint(vip[0]["name"])
		} else {
			v["vipName"] = "普通会员"
		}
	}
	c.Data["member"] = member
	vip := models.Query(`select name from mt_member_vip where gid=0 and status=1`)
	c.Data["vip"] = vip
	if id != "" {
		business := models.Query(`select a.id,a.uid,a.uids,b.monicker,b.name,b.sex,b.mobile,b.wechat,b.mail,b.address,c.pathname 
			from mt_business a 
		    left join mt_member b on a.uid=b.id 
		    left join mt_resources c on c.id=b.avatar 
		    where a.status=1 and a.id=?`, id)
		c.Data["info"] = business[0]
	}
	c.TplName = "admin/member/business_ae.html"
}

func (c *MemberBusinessAE) Post() {
	defer c.ServeJSON()
	js := make(map[string]interface{})
	c.Data["json"] = &js
	js["status"] = 0
	input := c.Input()
	input.Set("uids", strings.Replace(strings.Trim(strings.Join(c.GetStrings("uids"), ","), ","), ",,", ",", -1))
	now := sword.Gettimes("")
	if input.Get("id") == "" {
		input.Set("addtime", now)
	}
	input.Set("modifytime", now)
	input.Set("gid", c.Gid)
	if res, err := models.Save("mt_business", input); err != nil {
		beego.Debug(err)
		return
	} else {
		models.Exec(`update mt_member set business=1 where id=?`, input.Get("uid"))
		var r models.Mt_systems_record
		r.Tid = int(res)
		if input.Get("id") == "" {
			r.Way = 2
		} else {
			r.Way = 3
		}
		r.Addtime = sword.Timeget()
		r.Table = 80
		r.Uid, _ = strconv.Atoi(c.Qid)
		if _, err := models.Orm().Insert(&r); err != nil {
			beego.Debug(err)
		}
	}
	js["status"] = 1
}

type MemberBusinessContent struct {
	BaseController
}

func (c *MemberBusinessContent) Get() {
	id := c.GetString("id")
	stime := c.GetString("stime")
	etime := c.GetString("etime")
	c.Data["stime"] = stime
	c.Data["etime"] = etime
	c.Data["id"] = id
	business := models.Query(`select id,uids from mt_business where id=?`, id)[0]
	if business["uids"] != nil && business["uids"] != "" {
		uids := business["uids"].(string)
		gid := c.Gid
		page, page2, num := models.Pagechange(c.GetString("page"), "")
		c.Data["page"] = c.GetString("page")
		// vid := c.GetString("vid")
		search := c.GetString("search")
		lt := ` limit ` + page + `,` + num
		ob := ` order by a.addtime desc`
		// c.Data["vid"] = vid
		w := ` a.status=1 and a.censoring=1 and a.id in (` + uids + `)`
		if search != "" {
			w += ` and a.monicker like '%` + search + `%'`
		}
		member := models.Query(`select a.*,b.pathname from mt_member a 
				left join mt_resources b on a.avatar=b.id 
				where` + w + ob + lt)
		pageSql := `select count(a.id) as totals from mt_member a where` + w
		for _, people := range member {
			id := people["id"].(string)
			vip := models.Query(`select a.name from mt_member_vip a 
					left join mt_member_vip_order b on a.id = b.vid 
					where a.status = 1 and b.uid = ? and a.gid = ?`, id, gid)
			if vip != nil {
				people["vipName"] = fmt.Sprint(vip[0]["name"])
			}
		}
		for _, v := range member {
			uid := v["id"].(string)
			var w []string
			if stime != "" {
				w = append(w, `addtime>'`+stime+` 00:00:00'`)
			}
			if etime != "" {
				w = append(w, `addtime<'`+etime+` 23:59:59'`)
			}
			w = append(w, `uid=`+uid+` and gid=`+c.Gid)
			ws := strings.Join(w, ` and `)
			order := models.Query(`select money,status from mt_order where status<>0 and ` + ws)
			moneys := "0"
			remoneys := "0"
			willmoneys := "0"
			if order != nil {
				for _, v := range order {
					money := fmt.Sprint(v["money"])
					status, _ := strconv.Atoi(fmt.Sprint(v["status"]))
					if status > 1 && status <= 6 {
						moneys = sword.Sum(moneys, money)
						if status == 6 {
							remoneys = sword.Sum(remoneys, money)
						}
					} else if status == 1 {
						willmoneys = sword.Sum(willmoneys, money)
					}
				}
			}
			v["moneys"] = moneys
			v["remoneys"] = remoneys
			v["willmoneys"] = willmoneys
		}
		c.Data["info"] = member
		c.Data["paginator"] = models.Page(pageSql, page2, num)

		c.Data["url"] = `/admin/member/business_content?search=` + search + `&id=` + id + `&stime=` + stime + `&etime=` + etime + `&`
		// c.Data["vip"] = models.Query(`select * from mt_member_vip where status=1 and gid=?`, c.Gid)
	}
	c.Data["business"] = business
	c.TplName = "admin/member/business_content.html"
}

type MemberBusinessDelCustomer struct {
	BaseController
}

func (c *MemberBusinessDelCustomer) Get() {
	defer c.ServeJSON()
	js := make(map[string]interface{})
	c.Data["json"] = &js
	js["status"] = 0
	id := c.GetString("id")
	uid := c.GetString("uid")
	business := models.Query(`select uids from mt_business where id=?`, id)[0]
	uids := business["uids"].(string)
	reg, _ := regexp.Compile(`^` + uid + `,|,` + uid + `$|^` + uid + `$`)
	uids = reg.ReplaceAllString(uids, "")
	reg, _ = regexp.Compile(`,` + uid + `,`)
	uids = reg.ReplaceAllString(uids, ",")
	err := models.Exec(`update mt_business set uids='` + uids + `' where id=` + id)
	if err != nil {
		beego.Debug(err)
		return
	}
	js["status"] = 1
}
